﻿using Sustainalytics.Claims;
using Sustainalytics.Entities;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;

namespace Sustainalytics.GCCS.Service
{
    public static class GCCSClaimsCheckerExtensions
    {
        public static bool ValidateNonCompliantOrWatchlist(this IClaimsChecker claimsChecker, ApiController ctrl)
        {
            string routeKey = "overallAssessment";
            string overallAssessment;
            var queryDic = ctrl.Request.GetQueryNameValuePairs().ToDictionary(el => el.Key, el => el.Value);

            queryDic.TryGetValue(routeKey, out overallAssessment);

            bool valid;

            if (string.IsNullOrEmpty(overallAssessment))
            {
                // check for GC/WL
                bool validWL = claimsChecker.Validate(ctrl, new List<ResourceParameters> { new ResourceParameters { Key = routeKey, Value = "1" } });
                bool validNC = claimsChecker.Validate(ctrl, new List<ResourceParameters> { new ResourceParameters { Key = routeKey, Value = "2" } });

                valid = validWL || validNC;
            }
            else
            {
                // check specific overallAssessment
                valid = claimsChecker.Validate(ctrl, new List<ResourceParameters> { new ResourceParameters { Key = routeKey, Value = overallAssessment } });
            }

            return valid;
        }

        public static bool Validate(this IClaimsChecker claimsChecker, ApiController ctrl, List<ResourceParameters> parameters)
        {
            // get current principal
            var principal = (ClaimsPrincipal)ctrl.User;

            // get route prefix
            object[] attrs = ctrl.GetType().GetCustomAttributes(typeof(RoutePrefixAttribute), false);
            RoutePrefixAttribute routePrefixAttrs = attrs == null || attrs.Length == 0 ? null : attrs.Select(a => (RoutePrefixAttribute)a).FirstOrDefault();

            // get HTTP Method
            string httpMethod = ctrl.Request.Method.Method;

            bool valid = claimsChecker.Validate(
                claimsPrincipal: principal,
                resource: routePrefixAttrs == null ? null : routePrefixAttrs.Prefix,
                verb: httpMethod,
                parameters: parameters);

            return valid;
        }
    }
}
